package com.person.service.impl;

import cn.hutool.core.util.StrUtil;
import com.person.mapper.DepartmentMapper;
import com.person.model.dto.DepartmentDto;
import com.person.model.dto.generate.*;
import com.person.model.entity.Contacts;
import com.person.model.entity.Department;
import com.person.model.vo.ComplaintBaseInfoVo;
import com.person.service.ComplaintBaseInfoService;
import com.person.service.ExportService;
import com.person.util.WordFontStyleUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;

@Service
@Slf4j
public class ExportServiceImpl implements ExportService {

    @Resource
    private ComplaintBaseInfoService complaintBaseInfoService;
    @Resource
    private DepartmentMapper departmentMapper;

    //默认存档地址
    private String caseFiling = null;

    //文件名前缀
    private String preFileName = null;

    @Override
    public void export(Integer complaintInfoId) {
        ComplaintBaseInfoVo complaintBaseInfo = complaintBaseInfoService.getComplaintBaseInfoById(complaintInfoId);

        Department department = departmentMapper.selectById(complaintBaseInfo.getDepartmentId());
        //存档地址,默认为e:/
        caseFiling = department.getCaseFiling();

        //前缀文件名
        preFileName = Optional.ofNullable(complaintBaseInfo.getRegistrationNo()).orElse("default");
        //获取并创建存档地址
        String complainantName = complaintBaseInfo.getComplainantInfo().getName();
        String agentName = complaintBaseInfo.getAgentInfo().getName();
        LocalDate complaintDate = complaintBaseInfo.getComplaintDate();
        caseFiling = getOrCreateDirectory(caseFiling, complainantName, agentName, complaintDate);

        //投诉登记表导出
        exportComplaintRegistrationForm(complaintBaseInfo);

        //举报登记表导出
        exportReportRegistrationForm(complaintBaseInfo);

        //案件来源登记表导出
        String dateSource = exportCaseSourceRegistrationForm(complaintBaseInfo);

        LocalDate acceptanceDate = complaintBaseInfo.getAcceptanceDate();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String complaintDateFormat = complaintDate.format(formatter);
        int year = acceptanceDate.getYear();
        //============================变量======================================================
        if (complaintBaseInfo.getIsAcceptance() == 1) {
            //受理通知书
            NoticeOfAcceptanceRequest noticeOfAcceptanceRequest = new NoticeOfAcceptanceRequest();

            noticeOfAcceptanceRequest.setDocumentNumber("保徐市监〔" + year + "〕第" + complaintBaseInfo.getNumber() + "号");
            noticeOfAcceptanceRequest.setComplainantName(complainantName);
            noticeOfAcceptanceRequest.setReceiveDate(acceptanceDate);
            noticeOfAcceptanceRequest.setComplaintDesc(complaintBaseInfo.getComplaintDesc());
            noticeOfAcceptanceRequest.setAgentName(agentName);

            String[] splitPerson = complaintBaseInfo.getContactPerson().split(",");
            if (splitPerson.length >= 2) {
                noticeOfAcceptanceRequest.setContactPersons(new String[]{splitPerson[0], splitPerson[1]});
            } else {
                noticeOfAcceptanceRequest.setContactPersons(splitPerson);
            }
            String[] splitPhone = complaintBaseInfo.getContactPhone().split(",");
            noticeOfAcceptanceRequest.setContactPhone(splitPhone);
            noticeOfAcceptanceRequest.setSignatureDate(complaintBaseInfo.getAcceptanceDate());
            //=====================================================================================
            exportNoticeOfAcceptance(noticeOfAcceptanceRequest);

            //投诉中止调解决议书
            //============================变量======================================================
            ResolutionOnSuspensionOfMediationForComplaintsRequest resolutionOnSuspensionOfMediationForComplaintsRequest = new ResolutionOnSuspensionOfMediationForComplaintsRequest();

            resolutionOnSuspensionOfMediationForComplaintsRequest.setDocumentNumber("保徐市监〔" + year + "〕第" + complaintBaseInfo.getNumber() + "号");
            resolutionOnSuspensionOfMediationForComplaintsRequest.setComplainantName(complainantName);
            String[] split = complaintBaseInfo.getComplaintDesc().split("，");
            String complaintDescTmp = complaintBaseInfo.getComplaintDesc().substring(split[0].length() + 1);
            String complaintDesc = complaintDescTmp.substring(0, complaintDescTmp.length() - 1);
            resolutionOnSuspensionOfMediationForComplaintsRequest.setDisputeContent("经审查，关于" + complaintBaseInfo.getAgentInfo().getName() + complaintDesc + "投诉的调解过程中出现以下第〔" + complaintBaseInfo.getAcceptanceSituation()
                    + "〕项情形，依据《市场监督管理投诉举报处理暂行办法》的规定，我局决定终止调解。");
            resolutionOnSuspensionOfMediationForComplaintsRequest.setTerminationReasonIndex(3);
            resolutionOnSuspensionOfMediationForComplaintsRequest.setSignatureDate(complaintBaseInfo.getMediateDate());
            //=====================================================================================
            //导出
            exportResolutionOnSuspensionOfMediationForComplaints(resolutionOnSuspensionOfMediationForComplaintsRequest);
        } else {
            //不予受理通知书
            //============================变量======================================================
            NoticeOfNonAcceptanceRequest noticeOfNonAcceptanceRequest = new NoticeOfNonAcceptanceRequest();

            noticeOfNonAcceptanceRequest.setDocumentNumber("保徐市监〔" + year + "〕第" + complaintBaseInfo.getNumber() + "号");
            noticeOfNonAcceptanceRequest.setComplainantName(complainantName);
            noticeOfNonAcceptanceRequest.setReceiveDate(acceptanceDate);
            String[] split = complaintBaseInfo.getComplaintDesc().split("，");
            String s = complaintBaseInfo.getComplaintDesc().substring(split[0].length() + 1);
            noticeOfNonAcceptanceRequest.setDisputeContent("我局于" + complaintDateFormat + "收到你关于" + complaintBaseInfo.getAgentInfo().getName() + s.substring(0, s.length() - 1) + "的投诉。经审查，"
                    + "属以下第〔" + complaintBaseInfo.getAcceptanceSituation() + "〕项情形，依据《市场监督管理投诉举报处理暂行办法》的规定，我"
                    + "局决定不予受理。");
            noticeOfNonAcceptanceRequest.setTerminationReasonIndex(3);
            noticeOfNonAcceptanceRequest.setSignatureDate(acceptanceDate);
            //=====================================================================================
            exportNoticeOfNonAcceptance(noticeOfNonAcceptanceRequest);
        }

        if (complaintBaseInfo.getRegisterAcceptance().getIsRegister() == 1) {
            //立案告知书
            //============================变量======================================================
            NoticeOfFilingRequest noticeOfFilingRequest = new NoticeOfFilingRequest();

            noticeOfFilingRequest.setDocumentNumber("保徐市监〔" + year + "〕第" + complaintBaseInfo.getNumber() + "号");
            noticeOfFilingRequest.setComplainantName(complainantName);
            noticeOfFilingRequest.setAgentName(agentName);

            noticeOfFilingRequest.setReceiveDate(complaintBaseInfo.getComplaintDate());
            String[] complaintDescSplit = complaintBaseInfo.getComplaintDesc().split("，");
            noticeOfFilingRequest.setComplaintDesc(complaintBaseInfo.getComplaintDesc().substring(complaintDescSplit[0].length() + 1));
            noticeOfFilingRequest.setSignatureDate(complaintBaseInfo.getRegisterAcceptance().getRegisterDate());
            exportNoticeOfFiling(noticeOfFilingRequest);
            //导出立案审批表
            exportFilingApprovalForm(complaintBaseInfo, dateSource);
        } else {
            //不予立案告知书
            //============================变量======================================================
            NoticeOfNonFilingRequest noticeOfNonFilingRequest = new NoticeOfNonFilingRequest();

            noticeOfNonFilingRequest.setDocumentNumber("保徐市监〔" + year + "〕第" + complaintBaseInfo.getNumber() + "号");
            noticeOfNonFilingRequest.setComplainantName(complainantName);
            noticeOfNonFilingRequest.setAgentName(agentName);

            noticeOfNonFilingRequest.setReceiveDate(complaintBaseInfo.getComplaintDate());
            noticeOfNonFilingRequest.setComplaintDesc(complaintBaseInfo.getComplaintDesc());
            noticeOfNonFilingRequest.setSignatureDate(complaintBaseInfo.getRegisterAcceptance().getRegisterDate());
            //导出
            exportNoticeOfNonFiling(noticeOfNonFilingRequest);
            //不予立案审批表导出
            exportApprovalFormForRefusalOfFiling(complaintBaseInfo, dateSource);
        }
    }


    /**
     * 获取并创建指定目录
     *
     * @param baseDir 基础目录
     * @return 生成的目录路径
     */
    private String getOrCreateDirectory(String baseDir, String complainantName, String agentName, LocalDate complaintDate) {
        String yearMonthPath = complaintDate.getYear() + "/" + complaintDate.getMonthValue() + "/";
        //规则: 子目录：举报人姓名_被举报人名称_年月日，如：张三_保定某某酒业有限公司_20221212
        String subDir = complainantName + "_" + agentName + "_" + complaintDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String completePath = yearMonthPath + subDir;
        Path directoryPath = Paths.get(baseDir, completePath);

        try {
            if (!Files.exists(directoryPath)) {
                Files.createDirectories(directoryPath);
            }
        } catch (IOException e) {
            throw new RuntimeException("无法创建目录：" + directoryPath, e);
        }

        return directoryPath.toString();
    }


    /**
     * 立案告知书
     */
    private void exportNoticeOfFiling(NoticeOfFilingRequest request) {
        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("举报立案告知书.docx");
        //============================变量======================================================
        String documentNumber = request.getDocumentNumber();
        String complainantName = request.getComplainantName();
        String agentName = request.getAgentName();
        LocalDate receiveDate = request.getReceiveDate();
        String complaintDesc = request.getComplaintDesc();
        LocalDate signatureDate = request.getSignatureDate();
        //=====================================================================================

        // 创建一个新的Word文档
        XWPFDocument document = new XWPFDocument();

        // 创建标题段落
        XWPFParagraph titleParagraph = document.createParagraph();
        WordFontStyleUtil.setTitleStyle(titleParagraph, "举报立案告知书");

        // 创建编号段落
        XWPFParagraph numberParagraph = document.createParagraph();
        WordFontStyleUtil.setSubTitleStyle(numberParagraph, documentNumber);

        // 创建举报人段落
        XWPFParagraph reporterParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(reporterParagraph, complainantName + "：", false);

        // 创建正文段落
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        String s = complaintDesc.substring(0, complaintDesc.length() - 1);
        String content = "我局于" + receiveDate.format(formatter) + "收到你关于" + agentName
                + s + "的举报。经核查，我局决定予以立案。";


        XWPFParagraph contentParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(contentParagraph, content, true);

        // 创建特此告知段落
        XWPFParagraph noticeParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(noticeParagraph, "特此告知。", true);

        // 创建署名段落
        XWPFParagraph signatureParagraph = document.createParagraph();
        WordFontStyleUtil.setSignatureStyle(signatureParagraph, "保定市徐水区市场监督管理局");

        // 添加日期
        XWPFParagraph dateParagraph = document.createParagraph();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        WordFontStyleUtil.setSignatureStyle(dateParagraph, signatureDate.format(dateFormatter));

        try {
            // 保存文档
            try (FileOutputStream out = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName)) {
                document.write(out);
            }

            // 关闭文档
            document.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            log.info("文档已成功生成：举报立案告知书.docx");
        }

    }


    /**
     * 不予立案告知书
     */
    private void exportNoticeOfNonFiling(NoticeOfNonFilingRequest request) {

        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("举报不予立案告知书.docx");
        //============================变量======================================================
        String documentNumber = request.getDocumentNumber();
        String complainantName = request.getComplainantName();
        String agentName = request.getAgentName();
        LocalDate receiveDate = request.getReceiveDate();
        String complaintDesc = request.getComplaintDesc();
        LocalDate signatureDate = request.getSignatureDate();
        //=====================================================================================

        // 创建一个新的Word文档
        XWPFDocument document = new XWPFDocument();

        // 创建标题段落
        XWPFParagraph titleParagraph = document.createParagraph();
        WordFontStyleUtil.setTitleStyle(titleParagraph, "举报不予立案告知书");

        // 创建编号段落
        XWPFParagraph numberParagraph = document.createParagraph();
        WordFontStyleUtil.setSubTitleStyle(numberParagraph, documentNumber);

        // 创建举报人段落
        XWPFParagraph reporterParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(reporterParagraph, complainantName + "：", false);

        // 创建正文段落
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String[] split = complaintDesc.split("，");
        String s = complaintDesc.substring(split[0].length() + 1);
        String content = "我局于" + receiveDate.format(formatter) + "收到你关于" + agentName + s.substring(0, s.length() - 1) +
                "的举报。经核查，我局决定不予立案。";

        XWPFParagraph contentParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(contentParagraph, content, true);

        // 创建特此告知段落
        XWPFParagraph noticeParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(noticeParagraph, "特此告知。", true);

        // 创建署名段落
        XWPFParagraph signatureParagraph = document.createParagraph();
        WordFontStyleUtil.setSignatureStyle(signatureParagraph, "保定市徐水区市场监督管理局");

        // 添加日期
        XWPFParagraph dateParagraph = document.createParagraph();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        WordFontStyleUtil.setSignatureStyle(dateParagraph, signatureDate.format(dateFormatter));

        try {
            // 保存文档
            try (FileOutputStream out = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName)) {
                document.write(out);
            }

            // 关闭文档
            document.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            log.info("文档已成功生成：举报不予立案告知书.docx");
        }

    }

    private void exportNoticeOfAcceptance(NoticeOfAcceptanceRequest request) {

        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("投诉受理决定书.docx");
        //============================变量======================================================
        String documentNumber = request.getDocumentNumber();
        String complainantName = request.getComplainantName();
        String agentName = request.getAgentName();
        LocalDate receiveDate = request.getReceiveDate();
        String complaintDesc = request.getComplaintDesc();
        String[] contactPersons = request.getContactPersons();
        String[] contactPhone = request.getContactPhone();
        LocalDate signatureDate = request.getSignatureDate();
        //=====================================================================================

        // 创建一个新的Word文档
        XWPFDocument document = new XWPFDocument();

        // 创建标题段落
        XWPFParagraph titleParagraph = document.createParagraph();
        WordFontStyleUtil.setTitleStyle(titleParagraph, "投诉受理决定书");

        // 创建编号段落
        XWPFParagraph numberParagraph = document.createParagraph();
        WordFontStyleUtil.setSubTitleStyle(numberParagraph, documentNumber);

        // 创建投诉人段落
        XWPFParagraph complainantParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(complainantParagraph, complainantName + "：", false);

        // 创建正文段落
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String[] split = complaintDesc.split("，");
        String s = complaintDesc.substring(split[0].length() + 1);
        String desc = s.substring(0, s.length() - 1) + "的投诉。";
        String content = "我局于" + receiveDate.format(formatter) + "收到你关于" + agentName + desc +
                "经审查，符合《市场监督管理投诉举报处理暂行办法》规定的受理条件，我局决定受理。";
        XWPFParagraph contentParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(contentParagraph, content, true);

        HashSet<String> hashSet = new HashSet<>(Arrays.asList(contactPhone));
        String[] contactPhoneArray = hashSet.toArray(new String[0]);

        // 创建联系人段落
        String contactInfo = "（联系人：" + String.join("、", contactPersons) +
                "，联系电话：" + String.join("、", contactPhoneArray) + "）";
        XWPFParagraph contactParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(contactParagraph, contactInfo, true);

        // 创建特此告知段落
        XWPFParagraph noticeParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(noticeParagraph, "特此告知。", true);

        // 创建署名段落
        XWPFParagraph signatureParagraph = document.createParagraph();
        WordFontStyleUtil.setSignatureStyle(signatureParagraph, "保定市徐水区市场监督管理局");

        // 添加日期
        XWPFParagraph dateParagraph = document.createParagraph();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        WordFontStyleUtil.setSignatureStyle(dateParagraph, signatureDate.format(dateFormatter));

        try {
            // 保存文档
            try (FileOutputStream out = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName)) {
                document.write(out);
            }

            // 关闭文档
            document.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            log.info("文档已成功生成：投诉受理决定书.docx");
        }

    }

    private void exportNoticeOfNonAcceptance(NoticeOfNonAcceptanceRequest request) {
        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("投诉不予受理决定书.docx");
        //============================变量======================================================

        String documentNumber = request.getDocumentNumber();
        String complainantName = request.getComplainantName();
        String disputeContent = request.getDisputeContent();
        LocalDate signatureDate = request.getSignatureDate();

        //=====================================================================================

        // 创建一个新的Word文档
        XWPFDocument document = new XWPFDocument();

        // 创建标题段落
        XWPFParagraph titleParagraph = document.createParagraph();
        WordFontStyleUtil.setTitleStyle(titleParagraph, "投诉不予受理决定书");

        // 创建编号段落
        XWPFParagraph numberParagraph = document.createParagraph();
        WordFontStyleUtil.setSubTitleStyle(numberParagraph, documentNumber);

        // 创建投诉人段落
        XWPFParagraph complainantParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(complainantParagraph, complainantName + "：", false);

        // 创建正文段落
        XWPFParagraph contentParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(contentParagraph, disputeContent, true);

        // 创建情形列表段落
        String[] rejectionReasons = {
                "（一）投诉事项不属于市场监督管理部门职责，或者本行政机关不具有处理权限的；",
                "（二）法院、仲裁机构、市场监督管理部门或者其他行政机关、消费者协会或者依法成立的其他调解组织已经受理或者处理过同一消费者权益争议的；",
                "（三）不是为生活消费需要购买、使用商品或者接受服务，或者不能证明与被投诉人之间存在消费者权益争议的；",
                "（四）除法律另有规定外，投诉人知道或者应当知道自己的权益受到被投诉人侵害之日起超过三年的；",
                "（五）未提供《市场监督管理投诉举报处理暂行办法》第九条第一款和第十条规定的材料的；",
                "（六）法律、法规、规章规定不予受理投诉的其他情形。"
        };

        for (String rejectionReason : rejectionReasons) {
            XWPFParagraph reasonParagraph = document.createParagraph();
            WordFontStyleUtil.setContentStyle(reasonParagraph, rejectionReason, true);
        }

        // 创建特此告知段落
        XWPFParagraph noticeParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(noticeParagraph, "特此告知。", true);

        // 创建署名段落
        XWPFParagraph signatureParagraph = document.createParagraph();
        WordFontStyleUtil.setSignatureStyle(signatureParagraph, "保定市徐水区市场监督管理局");

        // 添加日期
        XWPFParagraph dateParagraph = document.createParagraph();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        WordFontStyleUtil.setSignatureStyle(dateParagraph, signatureDate.format(formatter));

        try {
            // 保存文档
            try (FileOutputStream out = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName)) {
                document.write(out);
            }

            // 关闭文档
            document.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            log.info("文档已成功生成：投诉不予受理决定书.docx");
        }

    }

    private void exportResolutionOnSuspensionOfMediationForComplaints(ResolutionOnSuspensionOfMediationForComplaintsRequest request) {
        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("投诉终止调解决定书.docx");
        //============================变量======================================================
        String documentNumber = request.getDocumentNumber();
        String complainantName = request.getComplainantName();
        String disputeContent = request.getDisputeContent();
        LocalDate signatureDate = request.getSignatureDate();
        //=====================================================================================

        // 创建一个新的Word文档
        XWPFDocument document = new XWPFDocument();

        // 创建标题段落
        XWPFParagraph titleParagraph = document.createParagraph();
        WordFontStyleUtil.setTitleStyle(titleParagraph, "投诉终止调解决定书");

        // 创建编号段落
        XWPFParagraph numberParagraph = document.createParagraph();
        WordFontStyleUtil.setSubTitleStyle(numberParagraph, documentNumber);

        // 创建投诉人段落
        XWPFParagraph complainantParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(complainantParagraph, complainantName + "：", false);

        // 创建正文段落
        XWPFParagraph contentParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(contentParagraph, disputeContent, true);

        // 创建情形列表段落
        for (int i = 1; i <= 7; i++) {
            XWPFParagraph situationParagraph = document.createParagraph();

            String situation = switch (i) {
                case 1 -> "（一）投诉人撤回投诉或者双方自行和解的；";
                case 2 -> "（二）投诉人与被投诉人对委托承担检定、检验、检测、鉴定工作的技术机构或者费用承担无法协商一致的；";
                case 3 ->
                    // 红框4：调解终止所属情形
                        "（三）投诉人或者被投诉人无正当理由不参加调解，或者被投诉人明确拒绝调解的；";
                case 4 -> "（四）经组织调解，投诉人或者被投诉人明确表示无法达成调解协议的；";
                case 5 -> "（五）自投诉受理之日起四十五个工作日内投诉人和被投诉人未能达成调解协议的；";
                case 6 ->
                        "（六）市场监督管理部门受理投诉后，发现存在《市场监督管理投诉举报处理暂行办法》第十五条规定情形的；";
                case 7 -> "（七）法律、法规、规章规定应当终止调解的其他情形。";
                default -> "";
            };
            WordFontStyleUtil.setContentStyle(situationParagraph, situation, true);
        }

        // 创建特此告知段落
        XWPFParagraph noticeParagraph = document.createParagraph();
        WordFontStyleUtil.setContentStyle(noticeParagraph, "特此告知。", true);

        // 创建署名段落
        XWPFParagraph signatureParagraph = document.createParagraph();
        WordFontStyleUtil.setSignatureStyle(signatureParagraph, "保定市徐水区市场监督管理局");

        // 添加日期
        XWPFParagraph dateParagraph = document.createParagraph();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        WordFontStyleUtil.setSignatureStyle(dateParagraph, signatureDate.format(formatter));

        try {
            // 保存文档
            try (FileOutputStream out = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName)) {
                document.write(out);
            }
            // 关闭文档
            document.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            log.info("文档已成功生成：投诉终止调解决定书.docx");
        }

    }

    private void exportFilingApprovalForm(ComplaintBaseInfoVo complaintBaseInfo, String dateSource) {

        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("立案审批表.docx");
        //=====================================================================================
        InputStream resourceAsStreamLiAn = getClass().getClassLoader().getResourceAsStream("templates/5立案审批表.docx");
        assert resourceAsStreamLiAn != null;
        XWPFDocument documentLiAn;
        try {
            documentLiAn = new XWPFDocument(resourceAsStreamLiAn);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 获取第一个表格
        XWPFTable tableLiAn = documentLiAn.getTables().get(0);

        // 假设我们要修改第二行的第二列数据
        XWPFTableCell cell1LiAn = tableLiAn.getRow(0).getCell(3);
        WordFontStyleUtil.setCellStyle(cell1LiAn, complaintBaseInfo.getAgentInfo().getName(), null);

        XWPFTableCell cell2LiAn = tableLiAn.getRow(1).getCell(3);
        WordFontStyleUtil.setCellStyle(cell2LiAn, complaintBaseInfo.getAgentInfo().getCreditCode(), null);//统一社会信用代码

        XWPFTableCell cell3LiAn = tableLiAn.getRow(2).getCell(3);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell3LiAn, complaintBaseInfo.getAgentInfo().getContactPerson(), null); //被投诉人名称

        XWPFTableCell cell4LiAn = tableLiAn.getRow(5).getCell(2);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell4LiAn, complaintBaseInfo.getAgentInfo().getAddress(), null); //被投诉人联系地址

        XWPFTableCell cell5LiAn = tableLiAn.getRow(6).getCell(1);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell5LiAn, complaintBaseInfo.getRegisterAcceptance().getCause(), null);//案由

        XWPFTableCell cell6LiAn = tableLiAn.getRow(7).getCell(1);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell6LiAn, dateSource, null);//收到材料时间

        XWPFTableCell cell7LiAn = tableLiAn.getRow(8).getCell(1);
        Department department = departmentMapper.selectById(complaintBaseInfo.getDepartmentId());
        String[] complaintDescSplit = complaintBaseInfo.getComplaintDesc().split("，");
        String substr = complaintBaseInfo.getComplaintDesc().substring(complaintDescSplit[0].length() + 1);
        String s = substr.replace(substr.charAt(substr.length() - 1), '，');

        String content = dateSource + "，我局接到" + complaintDescSplit[0] + "，投诉" + complaintBaseInfo.getAgentInfo().getName() + s
                + department.getNotRegisteredTerm() + complaintBaseInfo.getRegisterAcceptance().getSituation() + department.getRegisteredTerm();

        WordFontStyleUtil.setCellStyle(cell7LiAn, content, "核查情况及立案理由");

        FileOutputStream fosLiAn;
        try {
            fosLiAn = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            documentLiAn.write(fosLiAn);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fosLiAn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                documentLiAn.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                resourceAsStreamLiAn.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            log.info("文档已成功生成：立案审批表.docx");
        }
    }

    private void exportApprovalFormForRefusalOfFiling(ComplaintBaseInfoVo complaintBaseInfo, String dateSource) {

        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("不予立案审批表.docx");
        //=====================================================================================
        InputStream resourceAsStreamBuLiAn = getClass().getClassLoader().getResourceAsStream("templates/4不予立案审批表.docx");
        assert resourceAsStreamBuLiAn != null;
        XWPFDocument documentBuLiAn;
        try {
            documentBuLiAn = new XWPFDocument(resourceAsStreamBuLiAn);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 获取第一个表格
        XWPFTable tableBuLiAn = documentBuLiAn.getTables().get(0);

        // 假设我们要修改第二行的第二列数据
        XWPFTableCell cell1BuLiAn = tableBuLiAn.getRow(0).getCell(3);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell1BuLiAn, complaintBaseInfo.getAgentInfo().getName(), null);//被投诉人单位姓名

        XWPFTableCell cell2BuLiAn = tableBuLiAn.getRow(1).getCell(3);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell2BuLiAn, complaintBaseInfo.getAgentInfo().getCreditCode(), null); //统一社会信用代码

        XWPFTableCell cell3BuLiAn = tableBuLiAn.getRow(2).getCell(3);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell3BuLiAn, complaintBaseInfo.getAgentInfo().getContactPerson(), null); //被投诉人名称

        XWPFTableCell cell4BuLiAn = tableBuLiAn.getRow(5).getCell(2);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell4BuLiAn, complaintBaseInfo.getAgentInfo().getAddress(), null); //被投诉人联系地址

        XWPFTableCell cell5BuLiAn = tableBuLiAn.getRow(6).getCell(1);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell5BuLiAn, complaintBaseInfo.getRegisterAcceptance().getCause(), null);//案由

        XWPFTableCell cell6BuLiAn = tableBuLiAn.getRow(7).getCell(1);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell6BuLiAn, dateSource, null);//收到材料时间

        Department department = departmentMapper.selectById(complaintBaseInfo.getDepartmentId());
        XWPFTableCell cell7BuLiAn = tableBuLiAn.getRow(8).getCell(1);

        String[] complaintDescSplit = complaintBaseInfo.getComplaintDesc().split("，");
        String substr = complaintBaseInfo.getComplaintDesc().substring(complaintDescSplit[0].length() + 1);
        String desc = substr.replace(substr.charAt(substr.length() - 1), '，');
        String content = dateSource + "，我局接到" + complaintDescSplit[0] + "，投诉" + complaintBaseInfo.getAgentInfo().getName() + desc + complaintBaseInfo.getRegisterAcceptance().getSituation() + "，" + department.getNotRegisteredDesc();
        WordFontStyleUtil.setCellStyle(cell7BuLiAn, content, "核查情况及不予立案理由");

        FileOutputStream fosBuLiAn;
        try {
            fosBuLiAn = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            documentBuLiAn.write(fosBuLiAn);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fosBuLiAn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                documentBuLiAn.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                resourceAsStreamBuLiAn.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            log.info("文档已成功生成：不予立案审批表.docx");
        }
    }

    private String exportCaseSourceRegistrationForm(ComplaintBaseInfoVo complaintBaseInfo) {

        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("案件来源登记表.docx");
        //=====================================================================================
        String templateName;
        if ("投诉、举报".equals(complaintBaseInfo.getSource())) {
            templateName = "templates/3案件来源登记表_投诉举报.docx";
        } else if ("其他部门移送".equals(complaintBaseInfo.getSource())) {
            templateName = "templates/3案件来源登记表_其他部门移送.docx";
        } else {
            templateName = "templates/3案件来源登记表_上级交办.docx";
        }
        InputStream resourceAsStreamSource = getClass().getClassLoader().getResourceAsStream(templateName);
        assert resourceAsStreamSource != null;
        XWPFDocument documentSource;
        try {
            documentSource = new XWPFDocument(resourceAsStreamSource);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 获取第一个表格
        XWPFTable tableSource = documentSource.getTables().get(0);
        XmlCursor tableSourceCursor = tableSource.getCTTbl().newCursor();
        tableSourceCursor.toPrevSibling();
        // 在表格上方插入一个新段落
        XWPFParagraph newParagraphSource = documentSource.insertNewParagraph(tableSourceCursor);
        newParagraphSource.setIndentationFirstLine(24 * 240);
        // 设置段落内容
        XWPFRun runSource = newParagraphSource.createRun();
        runSource.setFontFamily("仿宋");
        runSource.setFontSize(14);
        runSource.setText("登记号：" + complaintBaseInfo.getRegistrationNo());

        XmlCursor xmlCursorSource = tableSource.getCTTbl().newCursor();
        // 将光标移动到表格之前
        if (xmlCursorSource.toPrevSibling()) {
            xmlCursorSource.removeXml();
        }
        newParagraphSource.setSpacingBefore(5);

        // 假设我们要修改第二行的第二列数据
        XWPFTableCell cell1Source = tableSource.getRow(1).getCell(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String dateSource = complaintBaseInfo.getComplaintDate().format(formatter);
        WordFontStyleUtil.setCellStyle(cell1Source, dateSource, null);//收到材料时间

        XWPFTableCell cell2Source = tableSource.getRow(6).getCell(4);
        WordFontStyleUtil.setCellStyle(cell2Source, complaintBaseInfo.getComplainantInfo().getName(), null); //起诉人名字

        XWPFTableCell cell3Source = tableSource.getRow(6).getCell(6);
        String idNo;
        if (complaintBaseInfo.getComplainantInfo().getIdNo() != null) {
            idNo = complaintBaseInfo.getComplainantInfo().getIdNo();
        } else {
            idNo = "/";
        }
        WordFontStyleUtil.setCellStyle(cell3Source, idNo, null); //起诉人身份证号

        XWPFTableCell cell4Source = tableSource.getRow(7).getCell(3);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell4Source, complaintBaseInfo.getComplainantInfo().getPhone(), null); //联系电话

        XWPFTableCell cell5Source = tableSource.getRow(8).getCell(3);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell5Source, complaintBaseInfo.getComplainantInfo().getAddress(), null); //起诉人地址

        if (complaintBaseInfo.getTransferDepartmentId() != null) {
            XWPFTableCell cell6Source = tableSource.getRow(9).getCell(3);// 注意：索引从0开始
            DepartmentDto departmentDto = complaintBaseInfo.getTransferDepartmentDto();
            WordFontStyleUtil.setCellStyle(cell6Source, departmentDto.getName(), null);//移送、交办部门名称
            Contacts contacts = departmentDto.getContactsList().get(0);
            XWPFTableCell cell7Source = tableSource.getRow(10).getCell(3);// 注意：索引从0开始
            WordFontStyleUtil.setCellStyle(cell7Source, contacts.getName(), null);//移送、交办部门联系人

            XWPFTableCell cell8Source = tableSource.getRow(10).getCell(5);// 注意：索引从0开始
            WordFontStyleUtil.setCellStyle(cell8Source, contacts.getPhone(), null);//移送、交办部门联系电话

            XWPFTableCell cell9Source = tableSource.getRow(11).getCell(3);// 注意：索引从0开始
            WordFontStyleUtil.setCellStyle(cell9Source, departmentDto.getAddress(), null);//移送、交办部门联系地址
        } else {
            XWPFTableCell cell6Source = tableSource.getRow(9).getCell(3);// 注意：索引从0开始
            WordFontStyleUtil.setCellStyle(cell6Source, "/", null);//移送、交办部门名称

            XWPFTableCell cell7Source = tableSource.getRow(10).getCell(3);// 注意：索引从0开始
            WordFontStyleUtil.setCellStyle(cell7Source, "/", null);//移送、交办部门联系人

            XWPFTableCell cell8Source = tableSource.getRow(10).getCell(5);// 注意：索引从0开始
            WordFontStyleUtil.setCellStyle(cell8Source, "/", null);//移送、交办部门联系电话

            XWPFTableCell cell9Source = tableSource.getRow(11).getCell(3);// 注意：索引从0开始
            WordFontStyleUtil.setCellStyle(cell9Source, "/", null);//移送、交办部门联系地址
        }
        XWPFTableCell cell10Source = tableSource.getRow(12).getCell(2);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell10Source, complaintBaseInfo.getAgentInfo().getName(), null);//当事人名字

        XWPFTableCell cell11Source = tableSource.getRow(13).getCell(2);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell11Source, complaintBaseInfo.getAgentInfo().getAddress(), null);//当事人住所

        XWPFTableCell cell12Source = tableSource.getRow(14).getCell(2);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell12Source, complaintBaseInfo.getAgentInfo().getContactPhone(), null);//当事人联系电话

        XWPFTableCell cell13Source = tableSource.getRow(15).getCell(1);// 注意：索引从0开始
        String[] complaintDescSplit = complaintBaseInfo.getComplaintDesc().split("，");
        WordFontStyleUtil.setCellStyle(cell13Source, dateSource + "，我局接到" + complaintDescSplit[0] + "，投诉" + complaintBaseInfo.getAgentInfo().getName() + complaintBaseInfo.getComplaintDesc().substring(complaintDescSplit[0].length() + 1), "案源内容");

        FileOutputStream fosSource;
        try {
            fosSource = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            documentSource.write(fosSource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fosSource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                documentSource.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                resourceAsStreamSource.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            log.info("文档已成功生成：案件来源登记表.docx");
        }
        return dateSource;
    }

    /**
     * 举报登记表
     *
     * @param complaintBaseInfo
     * @return
     */
    private void exportReportRegistrationForm(ComplaintBaseInfoVo complaintBaseInfo) {

        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("举报登记表.docx");
        //=====================================================================================
        InputStream resourceAsStreamJuBao = getClass().getClassLoader().getResourceAsStream("templates/2举报登记表.docx");
        assert resourceAsStreamJuBao != null;
        XWPFDocument documentJuBao;
        try {
            documentJuBao = new XWPFDocument(resourceAsStreamJuBao);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 获取第一个表格
        XWPFTable tableJuBao = documentJuBao.getTables().get(0);
        cellTitleText(tableJuBao, documentJuBao, complaintBaseInfo);
        // 假设我们要修改第二行的第二列数据
        XWPFTableCell cell1JuBao = tableJuBao.getRow(0).getCell(2);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell1JuBao, complaintBaseInfo.getComplainantInfo().getName(), null);//投诉人姓名

        XWPFTableCell cell2JuBao = tableJuBao.getRow(0).getCell(4);
        WordFontStyleUtil.setCellStyle(cell2JuBao, complaintBaseInfo.getComplainantInfo().getPhone(), null); //联系电话

        XWPFTableCell cell3JuBao = tableJuBao.getRow(1).getCell(2);
        WordFontStyleUtil.setCellStyle(cell3JuBao, complaintBaseInfo.getComplainantInfo().getAddress(), null); //住址

        XWPFTableCell cell4JuBao = tableJuBao.getRow(2).getCell(2);
        WordFontStyleUtil.setCellStyle(cell4JuBao, complaintBaseInfo.getAgentInfo().getName(), null); //被投诉人名称

        XWPFTableCell cell5JuBao = tableJuBao.getRow(3).getCell(2);
        WordFontStyleUtil.setCellStyle(cell5JuBao, complaintBaseInfo.getAgentInfo().getAddress(), null); //被投诉人联系地址

        XWPFTableCell cell6JuBao = tableJuBao.getRow(4).getCell(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String complaintDateFormat = complaintBaseInfo.getComplaintDate().format(formatter);
        String[] complaintDescSplit = complaintBaseInfo.getComplaintDesc().split("，");
        String content = complaintDateFormat + "，我局接到" + complaintDescSplit[0] + "，举报" + complaintBaseInfo.getAgentInfo().getName() + complaintBaseInfo.getComplaintDesc().substring(complaintDescSplit[0].length() + 1);
        WordFontStyleUtil.setCellStyle(cell6JuBao, content, "案源内容");//违法的法律法规

        FileOutputStream fosJuBao;
        try {
            fosJuBao = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            documentJuBao.write(fosJuBao);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fosJuBao.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                documentJuBao.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                resourceAsStreamJuBao.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            log.info("文档已成功生成：举报登记表.docx");
        }
    }

    /**
     * 投诉登记表导出
     *
     * @param complaintBaseInfo
     */
    private void exportComplaintRegistrationForm(ComplaintBaseInfoVo complaintBaseInfo) {

        //===========================文件名=====================================================
        // 使用格式化方法生成文件名
        String fileName = formatFileNameWithDate("投诉登记表.docx");
        //=====================================================================================

        InputStream resourceAsStreamTouSu = getClass().getClassLoader().getResourceAsStream("templates/1投诉登记表.docx");
        assert resourceAsStreamTouSu != null;
        XWPFDocument documentTouSu;
        try {
            documentTouSu = new XWPFDocument(resourceAsStreamTouSu);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 获取第一个表格
        XWPFTable tableTouSu = documentTouSu.getTables().get(0);
        cellTitleText(tableTouSu, documentTouSu, complaintBaseInfo);
        // 假设我们要修改第二行的第二列数据
        XWPFTableCell cell1TouSu = tableTouSu.getRow(0).getCell(2);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell1TouSu, complaintBaseInfo.getComplainantInfo().getName(), null);//投诉人姓名

        XWPFTableCell cell2TouSu = tableTouSu.getRow(0).getCell(4);
        WordFontStyleUtil.setCellStyle(cell2TouSu, complaintBaseInfo.getComplainantInfo().getPhone(), null);//联系电话

        XWPFTableCell cell3TouSu = tableTouSu.getRow(1).getCell(2);
        WordFontStyleUtil.setCellStyle(cell3TouSu, complaintBaseInfo.getComplainantInfo().getAddress(), null);//住址

        XWPFTableCell cell4TouSu = tableTouSu.getRow(2).getCell(2);
        WordFontStyleUtil.setCellStyle(cell4TouSu, complaintBaseInfo.getAgentInfo().getName(), null); //被投诉人名称

        XWPFTableCell cell5TouSu = tableTouSu.getRow(2).getCell(4);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell5TouSu, complaintBaseInfo.getAgentInfo().getContactPerson(), null); //被投诉人联系人

        XWPFTableCell cell6TouSu = tableTouSu.getRow(3).getCell(2);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell6TouSu, complaintBaseInfo.getAgentInfo().getAddress(), null);//被投诉人地址

        XWPFTableCell cell7TouSu = tableTouSu.getRow(3).getCell(4);// 注意：索引从0开始
        WordFontStyleUtil.setCellStyle(cell7TouSu, complaintBaseInfo.getAgentInfo().getContactPhone(), null);//被投诉人联系电话

        XWPFTableCell cell8TouSu = tableTouSu.getRow(4).getCell(1);// 注意：索引从0开始
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String complaintDateFormat = complaintBaseInfo.getComplaintDate().format(formatter);
        String[] complaintDescSplit = complaintBaseInfo.getComplaintDesc().split("，");
        String content = complaintDateFormat + "，我局接到" + complaintDescSplit[0] + "，投诉" + complaintBaseInfo.getAgentInfo().getName() + complaintBaseInfo.getComplaintDesc().substring(complaintDescSplit[0].length() + 1);
        WordFontStyleUtil.setCellStyle(cell8TouSu, content, "消费者权益争议事实");//消费者权益争议事实

        FileOutputStream fosTouSu;
        try {
            fosTouSu = new FileOutputStream(caseFiling + StrUtil.C_BACKSLASH + fileName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            documentTouSu.write(fosTouSu);

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fosTouSu.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                documentTouSu.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                resourceAsStreamTouSu.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            log.info("文档已成功生成：投诉登记表.docx");
        }
    }


    /**
     * 格式化文件名，将其前缀为当前日期
     *
     * @param originalFileName 原始文件名
     * @return 格式化后的文件名
     */
    private String formatFileNameWithDate(String originalFileName) {
        return preFileName + "-" + originalFileName;
    }

    private void cellTitleText(XWPFTable table, XWPFDocument document, ComplaintBaseInfoVo complaintBaseInfo) {
        // 获取表格的 XmlCursor
        XmlCursor tableJuBaoCursor = table.getCTTbl().newCursor();
        // 将光标移动到表格之前
        tableJuBaoCursor.toPrevSibling();
        // 在表格上方插入一个新段落
        XWPFParagraph newParagraph = document.insertNewParagraph(tableJuBaoCursor);
        newParagraph.setSpacingBefore(5);
        // 设置段落内容
        XWPFRun run = newParagraph.createRun();
        run.setFontFamily("仿宋_GB2312"); 
        run.setFontSize(14);
        Department department = departmentMapper.selectById(complaintBaseInfo.getDepartmentId());
        run.setText("登记单位：" + department.getName() + "                           编号：" + complaintBaseInfo.getNumber());

        XmlCursor xmlCursor = table.getCTTbl().newCursor();
        // 将光标移动到表格之前
        if (xmlCursor.toPrevSibling()) {
            xmlCursor.removeXml();
        }
    }
}
